package org.darkforest.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.Date;

public class CalculateUserAgeUtils {

    /**
     * 根据身份证号码，计算该用户在date当日的年龄
     * @param cardId 身份证号码
     * @param date
     * @return int
     */
    public static int calculate(String cardId, Date date) {
        int yearOfBirth = Integer.valueOf(StringUtils.substring(cardId, 6, 10));
        int monthOfBirth = Integer.valueOf(StringUtils.substring(cardId, 10, 12));
        int dayOfMonthOfBirth = Integer.valueOf(StringUtils.substring(cardId, 12, 14));

        Calendar now = Calendar.getInstance();
        now.setTime(date);
        int yearOfNow = now.get(Calendar.YEAR);
        int monthOfNow = now.get(Calendar.MONTH) + 1;
        int dayOfMonthOfNow = now.get(Calendar.DAY_OF_MONTH);

        int result = yearOfNow - yearOfBirth;
        if (monthOfNow < monthOfBirth || (monthOfNow == monthOfBirth && dayOfMonthOfNow < dayOfMonthOfBirth)) {
            result--;
        }

        return result;
    }
}
